package cn.wind.xboot.module.web.controller;

import cn.wind.xboot.core.res.ApiResult;
import cn.wind.xboot.logic.entity.Order;
import cn.wind.xboot.logic.entity.OrderGoods;
import cn.wind.xboot.logic.entity.StoreSteelyard;
import cn.wind.xboot.logic.service.IOrderGoodsService;
import cn.wind.xboot.logic.service.IOrderService;
import cn.wind.xboot.logic.service.IStoreSteelyardService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *消费订单
 * @author WangHao
 * @date 2019-04-02
 */
@Slf4j
@CrossOrigin
@RequestMapping("consumeOrder")
@Controller
public class ConsumeOrderController {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderGoodsService orderGoodsService;
    @Autowired
    private IStoreSteelyardService storeSteelyardService;

    @RequestMapping("/orderCreate")
    @ResponseBody
    public ApiResult orderCreate(String orderParams){
        Date date = new Date();
        //创建订单
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String orderNum = "";
        String serialNo = "";
        orderNum += sdf.format(date) + date.getTime();
        JSONObject jsonObject = JSONObject.fromObject(orderParams);
        //智能秤唯一识别码
        String deviceToken = jsonObject.getString("deviceToken");
        //智能秤信息
        StoreSteelyard steelyard = storeSteelyardService.findByDeviceToken(deviceToken);
        int countNum = orderService.countOrderByDay(steelyard.getSId());
        if (countNum==0){
            serialNo = "1";
        }
        serialNo = String.valueOf(countNum+1);
        //具体菜品信息
        JSONArray jsonArray = JSONArray.fromObject( jsonObject.getString("vegetables") );

        Order order = new Order();
        order.setCliId(steelyard.getMerchantId());
        order.setSId(steelyard.getSId());
        order.setStatus(1);
        order.setSerialNo(serialNo);
        order.setOrderNum(orderNum);
        //order.setAmountTotal(orderDto.getAmountTotal());
        order.setCreateTime(date);
        order.setUpdateTime(date);
        BigDecimal originalPrice = new BigDecimal( 0 );
        List<OrderGoods> orderGoodsList = new ArrayList<>();
        for (int i=0;i<jsonArray.size();i++){
            OrderGoods orderGoods = new OrderGoods();
            JSONObject object = jsonArray.getJSONObject(i);
            BigDecimal price = new BigDecimal( object.getString("vegetablePrice") );
            Double vegetableNum = Double.parseDouble( object.getString("vegetableWeight") );
            orderGoods.setCreateTime(date);
            orderGoods.setUpdateTime(date);
            orderGoods.setName(object.getString("vegetableName"));
            orderGoods.setNum(vegetableNum);
            orderGoods.setTotal( new BigDecimal( object.getString("vegetableTotalPrice") ) );
            orderGoods.setPrice(price);
            orderGoods.setOrderNum(orderNum);
            orderGoods.setSId(steelyard.getSId());
            //订单原价
            originalPrice = originalPrice.add( price.multiply( new BigDecimal(Double.toString( vegetableNum ))));
            orderGoodsList.add(orderGoods);
        }
        if (originalPrice.compareTo( new BigDecimal( jsonObject.getString("amount") ) ) != 0) {
            //前端计算后传来的总价格和我后台计算的不一样
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException("订单商品总价格异常！");
        }
        order.setOriginalPrice(originalPrice);
        //生成订单
        orderService.saveOrUpdate(order);
        //生成订单商品明细
        for (OrderGoods o : orderGoodsList) {
            o.setOrderId(order.getId());
            orderGoodsService.saveOrUpdate(o);
        }
        return ApiResult.Custom().success("订单创建成功");
    }
}
